package com.atguigu.gmall.order.interceptor;


import com.atguigu.gmall.order.vo.UserInfo;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author Jia Fa
 * @create 2021-12-19 18:48
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {

    // 声明线程的局部变量  独属于某一线程 可避免线程安全问题
    private static final ThreadLocal<UserInfo> THREAD_LOCAL = new ThreadLocal<>();



    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String userId = request.getHeader("userId");
        String username = request.getHeader("username");


        // 把信息放入局部变量中供后续服务使用
        THREAD_LOCAL.set(new UserInfo(Long.valueOf(userId),null,username));
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

        // 调用删除方法 由于使用的是tomcat线程池, 线程结束后不会回收
        // 线程内部的强引用变量不会被GC回收 逐渐导致OOM
        THREAD_LOCAL.remove();
    }

    /**
     * 封装一个获取线程局部变量值的静态方法
     * @return
     */
    public static UserInfo getUserInfo(){
        return THREAD_LOCAL.get();
    }
}
